﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using UMC.Net;
using System.IO;
using System.Collections;
using UMC.Data;

namespace UMC.Web
{
    /// <summary>
    /// 交互上下文
    /// </summary>
    public class WebContext
    {
        static WebContext()
        {
            if (WebRuntime.isScanning() == false)
            {
                UMC.Data.Reflection.Instance().ScanningClass();
            }
        }
        public NetLoger Loger => this.runtime.Client.Context.Loger;
        public int RedirectTimes
        {
            get
            {
                return this.runtime.Client.RedirectTimes;
            }
        }

        internal WebRuntime runtime;
        
        public ByteChunk Memory => this.runtime.Client.Context.Memory;

        public WebClient Client => this.runtime.Client;

        internal WebContext(WebRuntime runtime)
        {
            this.runtime = runtime;
        }
        /// <summary>
        /// 触发关闭客户端事件
        /// </summary>
        public void Close()
        {
            this.Response.ClientEvent |= WebEvent.Close;
            // this.End();
        }


        public void Reset()
        {
            this.Response.ClientEvent |= WebEvent.Reset;
        }
        public void Reset(WebMeta reset)
        {
            this.Response.ClientEvent |= WebEvent.Reset;
            this.Response.Headers.Put("Reset", reset);
        }
        public void Send(WebMeta data, bool endResponse)
        {
            if (data.ContainsKey("type") == false)
            {
                data.Put("type", $"{this.Request.Model}.{this.Request.Command}");
            }
            SendJSON(data, endResponse);
        }
        /// <summary>
        /// 向发送客户端发送数据事情
        /// </summary>
        /// <param name="data">发送的数据</param>
        /// <param name="endResponse"></param>
        internal void SendJSON(Data.IJSON data, bool endResponse)
        {
            WebResponse response = this.Response;
            response.ClientEvent |= WebEvent.DataEvent;
            if (response.Headers.ContainsKey("DataEvent"))
            {
                var ts = response.Headers.GetDictionary()["DataEvent"];

                if (ts is Array)
                {
                    var ats = new System.Collections.ArrayList();
                    ats.AddRange((Array)ts);
                    ats.Add(data);

                    response.Headers.Put("DataEvent", ats.ToArray());
                }
                else
                {
                    response.Headers.Put("DataEvent", new object[] { ts, data });
                }

            }
            else
            {

                response.Headers.Put("DataEvent", data);
            }
            if (endResponse)
            {
                this.End();
            }

        }
        public void Send(UIClick click, bool endResponse)
        {
            this.SendJSON(new WebMeta().Put("type", "Click").Put("Click", click), endResponse);
        }
        /// <summary>
        /// 向发送客户端发送数据事情
        /// </summary>
        /// <param name="type">数据事件</param>
        /// <param name="data">发送的数据</param>
        /// <param name="endResponse"></param>
        public void Send(String type, WebMeta data, bool endResponse)
        {
            this.SendJSON(data.Put("type", type), endResponse);
        }
        /// <summary>
        /// 向发送客户端发送数据事情
        /// </summary>
        /// <param name="type">数据事件</param>
        /// <param name="endResponse"></param>
        public void Send(String type, bool endResponse)
        {
            // WebMeta data = new WebMeta();
            SendJSON(new WebMeta("type", type), endResponse);
        }
        public void Send(bool endResponse)
        {
            SendJSON(new WebMeta("type", $"{this.Request.Model}.{this.Request.Command}"), endResponse);
        }
        public void UIEvent(string name, string value, bool endResponse)
        {
            this.UIEvent(new WebMeta().Put("key", name).Put("value", new WebMeta("Value", value)), endResponse);
        }
        public void UIEvent(string name, IJSON value, bool endResponse)
        {
            this.UIEvent(new WebMeta().Put("key", name).Put("value", value), endResponse);
        }
        public void UIEvent(string name, string ui, string value, bool endResponse)
        {
            this.UIEvent(name, ui, new WebMeta("Value", value), endResponse);
        }
        public void UIEvent(string name, string ui, IJSON value, bool endResponse)
        {
            switch ((ui ?? "none").ToLower())
            {
                case "":
                case "none":
                    UIEvent(new WebMeta().Put("key", name).Put("value", value), endResponse);
                    break;
                default:
                    UIEvent(new WebMeta().Put("key", name).Put("ui", ui).Put("value", value), endResponse);
                    break;
            }
        }
        private void UIEvent(WebMeta webMeta, bool endResponse)
        {

            this.Response.Headers.Put("UIEvent", webMeta);
            this.Response.ClientEvent = this.Response.ClientEvent | WebEvent.UIEvent;
            if (endResponse)
                this.Response.End();
        }



        /// <summary>
        /// 触发客户端从新获取可用命令
        /// </summary>
        public void OnReset()
        {
            this.Response.ClientEvent |= WebEvent.Reset;
        }

        public void Error(Exception error)
        {
            if (error is WebAbortException)
            {
                this.OutputFinish();
            }
            else
            {
                this.Client.Context.Error(error);
            }

        }
        /// <summary>
        /// 当前的正在处理路线
        /// </summary>
        public WebFlow CurrentFlow => runtime.CurrentFlow;

        public UMC.Security.AccessToken Token => runtime.Client.Token;

        public string Server => runtime.Client.Server;
        /// <summary>
        /// 当前正在处理活动
        /// </summary>
        public WebActivity CurrentActivity => runtime.CurrentActivity;

        /// <summary>
        /// 当前正在处理的POSFlowFactory
        /// </summary>
        public IWebFactory FlowFactory => runtime.CurrentFlowFactory;


        /// <summary>
        /// 路模块共享的数据键
        /// </summary>
        public System.Collections.IDictionary Items => runtime.Client.Items;

        /// <summary>
        /// 终止当前请求，并返回终端
        /// </summary>
        public void End()
        {
            throw new WebAbortException();
        }
        /// <summary>
        /// 请求信息
        /// </summary>
        public WebRequest Request => runtime.Request;

        /// <summary>
        /// 异步处理完成
        /// </summary>
        public void OutputFinish()
        {
            runtime.Client.Atfer(this);
        }
        /// <summary>
        /// 响应信息
        /// </summary>
        public WebResponse Response => runtime.Response;
        public Guid? AppKey => runtime.Client.Context.AppKey;
    }
}
